import { Spin } from 'antd';
import { Suspense, useMemo } from 'react';
import { Switch, Route, useLocation, Redirect } from 'react-router-dom';
import GlobalFooter from './components/Footers';
import GlobalHeader from './components/Headers';
import RouterWrapper from './components/RouterWrapper';
import { HIDDIEN_FOOTER_PATHS, HIDDIEN_HEADER_PATHS } from './const';
import routesConfig from './routes';
import { useUserInfo } from './store/user/hooks';
import { autoLogin, getUserCookies } from './utils/account';
import { useDispatch } from 'react-redux';
import { updateUserInfo } from './store/user';

const useShow = (paths: string[], dep) => {
  return useMemo(
    () => paths.filter((item) => dep.startsWith(item)).length,
    [dep, paths],
  );
};

const App = () => {
  const location = useLocation();
  const dispatch = useDispatch();

  const userKey = getUserCookies();

  // 获取用户信息
  const userInfo = useUserInfo();

  // 自动登录
  if (userKey && !userInfo.uid) {
    autoLogin(userKey)
      ?.then((res) => {
        // 更新redux的用户信息
        dispatch(updateUserInfo('setUserInfo')(res));
      })
      .catch((err) => {
        console.log(err);
      });
  }

  // 是否隐藏footer组件
  const hiddenFooter = useShow(HIDDIEN_FOOTER_PATHS, location.pathname);

  // 是否隐藏header组件
  const hiddenHeader = useShow(HIDDIEN_HEADER_PATHS, location.pathname);

  const height = useMemo(
    () => 87 + (hiddenFooter ? 5 : 0) + (hiddenHeader ? 8 : 0) + 'vh',
    [hiddenFooter, hiddenHeader],
  );

  return (
    <div
      className='min-h-screen relative bg-smart-gray'
      style={
        hiddenFooter
          ? { minWidth: '100vw', overflow: 'hidden' } // 这里overfolw的问题待解决
          : { minWidth: '100vw' }
      }>
      {/* 顶部组件 */}
      {!hiddenHeader && <GlobalHeader />}
      <div
        style={{
          minHeight: height,
          height,
        }}>
        {/* 加载组件 */}
        <Suspense
          fallback={
            <div className='w-full h-full flex items-center justify-center'>
              <Spin size='large' />
            </div>
          }>
          <Switch>
            {/* 跟路径重定向到chat */}
            <Route exact path='/'>
              <Redirect to='/chat' />
            </Route>
            {routesConfig.map((item, index) => (
              <Route
                key={index}
                path={item.path}
                exact={item.exact}
                component={() => (
                  <item.innerComponent
                    userInfo={userInfo}></item.innerComponent>
                )}
              />
            ))}
          </Switch>
        </Suspense>
      </div>
      {!hiddenFooter && <GlobalFooter />}
    </div>
  );
};

export default RouterWrapper(<App />);
